from collections import defaultdict
from typing import List


class Solution:
    def maxSum(self, nums: List[int], m: int, k: int) -> int:
        d = defaultdict(int)
        ans = tem = pre = 0
        for i in range(k-1):
            tem  += nums[i]
            d[nums[i]] += 1
        for i in range(k-1,len(nums)):
            tem += nums[i]
            d[nums[i]] += 1
            if len(d.keys()) >= m:
                ans = max(tem,ans)
            d[nums[pre]] -= 1
            tem -= nums[pre]
            if d[nums[pre]] == 0:
                d.pop(nums[pre])
            pre += 1
        return ans
